<template>
  <el-form
    v-if="showForm"
    ref="form"
    v-bind="config"
    :model="form"
    label-width="auto"
    :rules="rules">
    <el-row
      type="flex"
      class="Row">
      <el-col
        v-for="(item,index) in fields"
        v-show="!item.hide"
        :key="index"
        :span="item.span">
        <el-form-item
          v-if="!item.hide"
          :label="item.label"
          :prop="item.notVerify?null:item.key">
          <template
            v-if="item.type=='slot'">
            <slot
              :name="item.soltName"
              :form="form"
              :item="item" />
          </template>
          <template v-else>
            <form-element
              :item="item"
              :fields="form"
              @uploadComplete="uploadCompleteCb">
            </form-element>
          </template>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
  import formElement from './element'
  export default {
    components: {
      formElement
    },
    props: {
      config: {
        type: Object,
        default: () => ({
          'label-suffix': ':',
          'label-width': 'auto'
        })
      },
      validateAfter: {
        type: Function,
        default: null
      },
      resetAfter: {
        type: Function,
        default: null
      },
      fields: {
        type: Array,
        required: true
      },
      rules: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        form: {},
        showForm: false
      }
    },
    mounted() {
      this.fields.forEach(item => {
        this.$set(this.form, item.key, item.defaultVal)
      })
      this.showForm = true
    },
    methods: {
      // 附件上传完成 更改附件id
      uploadCompleteCb(fileList) {
        if (this.form.hasOwnProperty('fileId')) {
          this.$set(this.form, 'fileId', fileList.length ? 1 : null)
        }
      },
      validate(cb) {
        return new Promise(resolve => {
          this.$refs.form.validate((valid) => {
            if (valid) {
              if (this.validateAfter && this.validateAfter instanceof Function) {
                this.validateAfter(this.form)
              }
            } else {
              cb && cb()
            }
            resolve({ valid: valid, formData: this.form })
          })
        })
      },
      resetForm() {
        this.$refs.form.resetFields()
        for (const i in this.form) {
          this.form[i] = null
        }
        if (this.resetAfter && this.resetAfter instanceof Function) {
          this.resetAfter(this.form)
        }
      },
      getFormData() {
        return this.form
      }
    }
  }
</script>
<style lang="scss" scoped>
  .Row{
    flex-wrap: wrap;
  }
</style>
